package com.zlm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlm.common.CustomException;
import com.zlm.common.Result;
import com.zlm.entity.*;
import com.zlm.mapper.OrdersMapper;
import com.zlm.service.*;
import com.zlm.utils.BaseHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    // 这个是我们用来查询用户的购物车的数据
    @Autowired
    private ShoppingCartService shoppingCartService;

    // 查询用户信息用的
    @Autowired
    private UserService userService;

    // 查询用户地址用的
    @Autowired
    private AddressBookService addressBookService;

    // 注入的订单明细
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @Override // 操作三张表
    @Transactional  // 操作多个数据库所以我们要加上事务
    public Result<String> submit(Orders orders) {
        // 1.获得当前用户id
        Long userId = BaseHolder.getCurrentId();
        // 2.查询用户购物车
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);

        // 2.1得到用户的购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            // 表示你购物车没有物品 不能下单
            throw new CustomException("购物车为空,不能下单");
        }

        // 2.2 查询用户数据
        User user = userService.getById(userId);
        // 2.3 查询地址信息
        // 从ordes里面取出我们的地址id
        Long addressBookId = orders.getAddressBookId();
        // 2.3.1 得到地址信息
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("无法得到地址信息,下单失败");
        }

        // 初始为0
        AtomicInteger amount = new AtomicInteger(0);

        // 2.4 生成订单号
        long orderId = IdWorker.getId();

        // 封装订单明细 就是orderdetial
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber()); // 数量
            orderDetail.setDishFlavor(item.getDishFlavor()); // 口味
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName()); // 菜品名称
            orderDetail.setImage(item.getImage()); // 图片名称
            orderDetail.setAmount(item.getAmount()); // 单个金额
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //addAndGet 表示 +=   multiply 表示 乘    BigDecimal封装了一下 item.getNumber()就是我们的份数


        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2); //正在派送
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //
        // 3.完成下单(向订单表插入一条数据)
        save(orders);

        // 4.向订单明细表插入数据(里面放的就是我们买的哪些东西 有可能有套餐和菜品一起)
        orderDetailService.saveBatch(orderDetails);

        // 5.清空购物车
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        return Result.success("下单成功");
    }
}
